package cn.edu.uestc.framework.exception;

import cn.edu.uestc.cwdsj.utils.CfgUtil;
import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;

import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;

/**
 * 动态加载业务异常
 * Created by Eric on 2017/6/9.
 */
public class TKBusinessExceptionMap {
    private static HashMap<Integer, String> exMap = new HashMap<Integer, String>();
    private Logger logger = Logger.getLogger(this.getClass());

    public static String map2String() {
        return exMap.toString();
    }

    private String exListsFilePath;

    public void init() throws DocumentException, IOException {
        Document exList = CfgUtil.getXMLDocument(exListsFilePath);
        Element exsDom = exList.getRootElement().element("exceptions");
        Iterator exIterator = exsDom.elementIterator("exception");
        while (exIterator.hasNext()) {
            Element ex = (Element) exIterator.next();
            TKBusinessExceptionMap.exMap.put(Integer.parseInt(ex.attributeValue("code")), ex.attributeValue("info"));
        }

        logger.info("[Business Ex] : 成功加载异常列表。");
    }

    public static String getInfo(int id) {
        StringBuilder stringBuilder = new StringBuilder();
        return stringBuilder.append("[").append(id).append("]").append(TKBusinessExceptionMap.exMap.get(id)).toString();
    }

    public void setExListsFilePath(String exListsFilePath) {
        this.exListsFilePath = exListsFilePath;
    }

    public String getExListsFilePath() {
        return exListsFilePath;
    }
}
